﻿package com.athena.ui {
	
	import flash.display.*;
	import flash.events.*;
	import flash.geom.Rectangle;
	import flash.text.TextField;
	
	public class Scrollbar extends Sprite
	{
		public var value:Number;
		public var padding:Number = 5;
		
		private var _textField:TextField;
		private var max:Number;
		private var min:Number;
		
		public function Scrollbar()
		{
			draw(width,height);
			drag_mc.addEventListener(MouseEvent.MOUSE_DOWN, dragHandle);
		}
		
		public function draw(w:Number,h:Number):void
		{
			scaleX = scaleY = 1;
			bar_mc.height = h - (up_btn.height - padding) * 2;
			bar_mc.y = up_btn.height - padding;
			down_btn.y = bar_mc.height + bar_mc.y - padding;
			min = bar_mc.y;
			max = bar_mc.height - drag_mc.height;
			drag_mc.y = min;
		}
		
		private function dragHandle(event:MouseEvent):void
		{
			drag_mc.startDrag(false, new Rectangle(0,min,0,max));
			stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
			stage.addEventListener(MouseEvent.MOUSE_MOVE, updateValue);
		}
		
		private function stopDragging(event:MouseEvent):void
		{
			drag_mc.stopDrag();
			stage.removeEventListener(MouseEvent.MOUSE_UP, stopDragging);
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, updateValue);
		}
		
		private function updateValue(event:MouseEvent = null):void
		{
			value = (drag_mc.y - min) / max;
			if(_textField && event)
			{
				_textField.scrollV = Math.round(value * _textField.maxScrollV);
			}
			dispatchEvent(new Event(Event.CHANGE));
		}
		
		private function clickScrollButton(event:MouseEvent):void
		{
			var percent:Number;
			_textField.scrollV += (event.currentTarget == up_btn) ? -1 : 1;
			percent = (_textField.scrollV - 1) / (_textField.maxScrollV - 1);
			drag_mc.y = percent * max + min;
			updateValue();
		}
		
		public function set textField(tf:TextField):void
		{
			_textField = tf;
			up_btn.addEventListener(MouseEvent.CLICK, clickScrollButton);
			down_btn.addEventListener(MouseEvent.CLICK, clickScrollButton);
		}
		
		public function get textField():TextField
		{
			return _textField;
		}
	}
}